package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


@Slf4j
@RestController
public class LoginController {

    @Autowired
    private EmpService empService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public Result login(@RequestBody Emp emp) {
        log.info("登录");
        //  1. 验证码校验
        Object verifCode = redisTemplate.opsForValue().get("verify:" + emp.getVerifCode());
        if (!emp.getVerifCode().equals(verifCode)) {
            return Result.error("验证码错误");
        }

        // 验证通过后删除验证码
        redisTemplate.delete("verify:" +emp.getVerifCode() );
        LoginInfo loginInfo=empService.login(emp);
        if (loginInfo==null){
            return Result.error("用户名或密码错误");
        }
            return Result.success(loginInfo);
    }
}
